import json
import os.path

from src.common.logger import getLogger
from flask import Blueprint, Response, request, send_file
from src.modules.rag.service import document_service

logger = getLogger()
api = Blueprint("document", __name__)

@api.route('/document/list', methods = ['GET'])
def document_list():
    args = request.args
    logger.info(f"document_list args: {args}")

    list = document_service.select_document_page(args)
    logger.info(f"document_list list len: {len(list)}")
    return Response(json.dumps({ "code": 200, "data": list }), status = 200, mimetype = "application/json")

@api.route('/document/delete', methods = ['POST'])
def document_delete():
    args = request.form
    logger.info(f"document_list args: {args}")

    document_service.delete_document_record(args)
    list = document_service.select_document_page(args)
    logger.info(f"document_list list len: {len(list)}")
    return Response(json.dumps({ "code": 200, "data": list }), status = 200, mimetype = "application/json")

@api.route("/document/upload", methods=['POST'])
def upload_document():
    if 'file' not in request.files:
        return Response(json.dumps({ "code": 500, "message": "没有上传任何文件" }), status = 200, mimetype = "application/json")

    file = request.files.get("file")
    document_service.upload_document(file)
    return Response(json.dumps({ "code": 200, "data": "", "message": "上传成功" }), status = 200, mimetype = "application/json")

@api.route("/document/website", methods=['POST'])
def upload_website():
    website = request.form.get("website")
    logger.info(f"upload_website website: {website}")

    document_service.upload_website(website)
    return Response(json.dumps({ "code": 200, "data": "", "message": "上传成功" }), status = 200, mimetype = "application/json")

@api.route('/document/preview', methods = ['GET'])
def preview_document():
    args = request.args
    logger.info(f"document_list args: {args}")

    content = document_service.preview_document(args)
    return Response(json.dumps({ "code": 200, "data": content }), status = 200, mimetype = "application/json")

@api.route("/document/download", methods=['POST'])
def download_document():
    args = request.form

    save_path = "D:/Downloads/taixu/documents"
    file_path = os.path.join(save_path, args.get("documentName"))
    return send_file(file_path, as_attachment = True, download_name = args.get("documentName"))
